<template>
  <div class="login_container">
    <div class="login_box">
        <!-- 头像区 -->
        <div class="avatar_box">
            <img src="../../assets/img/jhLogo.png" alt="">
        </div>
        <div class="titel">高线厂辊环管理系统</div>
        <!-- 表单登录区域 -->
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">                   
            <el-form-item prop="username">
                <el-input v-model="loginForm.username" prefix-icon="iconfont icon-touxiang" placeholder="请输入用户名" @keyup.enter.native="login"></el-input>
            </el-form-item>
            <!-- 密码 -->
             <el-form-item prop="password">
                <el-input  v-model="loginForm.password" prefix-icon="iconfont icon-mima" type="password" placeholder="请输入密码" @keyup.enter.native="login" :autofocus="true"></el-input>
            </el-form-item>
             <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">
              记住密码
            </el-checkbox>
            <!-- 按钮区域 -->
            <el-form-item class="btns">
               <el-button type="primary" @click="login" :loading="loading">登录</el-button>
               <el-button type="info" @click="resetLoginForm">重置</el-button>              
            </el-form-item>
            <el-form-item class="register" style="width: 100%">
              <div class="register">
                 <a class="forget" href="" >忘记密码?</a>
                 <a href="/register" >注册</a>               
              </div>              
            </el-form-item>           
        </el-form>        
    </div>    
  </div>
</template>

<script>
import Cookies from 'js-cookie'
export default {  
  name: 'Login',
  data () {
    return {        
        loginForm: {
            username: '',
            password: '',
            rememberMe: false
        },
        loginFormRules: {
         username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 5 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, message: '长度不少于6个字符', trigger: 'blur' }
          ]
        },
        loading: false
    }
  },
    watch: {
  },
    created () {
      this.getCookie()
       // token 过期提示
      this.point()
  },
    methods: {
      point() {
        const point = Cookies.get('point') !== undefined
        if (point) {
          this.$notify({
            title: '提示',
            message: '当前登录状态已过期，请重新登录！',
            type: 'warning',
            duration: 5000
          })
          Cookies.remove('point')
        }
      },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
        // 点击点击重置按钮
    resetLoginForm () {
      this.$refs.loginFormRef.resetFields()
    },
    login () {
      
      this.$refs.loginFormRef.validate(async valid => {
        // 表单预验证
        if (!valid) return
        this.loading = true
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe        
        }

        if (user.rememberMe) {
            Cookies.set('username', user.username, {
              expires: 30
            })
            Cookies.set('password', user.password, {
              expires: 30
            })
            Cookies.set('rememberMe', user.rememberMe, {
              expires: 30
            })
        } else {
          Cookies.remove('username')
          Cookies.remove('password')
          Cookies.remove('rememberMe')
        }

        await this.$http.post('/login/userLogin', this.getData).then( ({ data:res }) =>{         
          this.loading = false
          if (res.code !== 2000) {
            return this.$message.error(res.msg)              
          }else{
            this.$message.success('登录成功')
            this.$store.commit('setUsername',user)  //存储登录状态
            // 将登录后的token,保存到客户端的 sessionStorage 中
            window.sessionStorage.setItem('token', res.token)
            window.sessionStorage.setItem('username', user.username)
            // 通过编程式导航跳转到后台主页，路由地址是/home
            this.$router.push('/home')
          } 
        }).catch(error =>{
           console.log('请求失败'+ error)
           this.loading = false
        })             
      })
    }
  },
  computed: {
      getData() {
        /* formData格式提交： */
        const formData = new FormData()
        for (var key in this.loginForm) {
            formData.append(key, this.loginForm[key])
        }
        return formData
      }
  }
}
</script>

<style scoped>
.login_container{
  /* background-color: #8397aa; */
  height: 100%;
  background-image:url('../../assets/img/ng.png');
}
.login_box{
  width: 450px;
  height:430px;
  background-color: #FFF;
  border-radius:3px;   /* 圆角边框 */

  /* div居中 */
  position: absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);   /* 横轴位移自身-50%，纵轴自身-50%*/
}
.titel{
  width: 100%;
  text-align: center;
  margin: 70px 0px;  
  font-size: 26px; 
}
.avatar_box{
  width: 70px;
  height: 70px;
  border-radius: 50%;    /* 边框变成圆形 */
  border: 1px solid #eee;
  padding: 10px;
  box-shadow: 0 0 10px;  /* 边框加阴影 */
  position: absolute;
  left:50%;
  transform: translate(-50%,-50%);
  background-color: #fff;
 }
.avatar_box img{
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #eee;
}

.login_form{
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 20px;
    box-sizing:border-box;
}
.btns{
    display: flex;   /* 变成弹性盒模型 */
    justify-content:center;   /*中间对齐 */
    margin: 0 0;
    width: 100%;
}

.register {
  float: right;
  margin: 4px;
}

.forget{
  margin: 0px 20px;
}

</style>
